package net.tavion.angelboot.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.tavion.angelboot.common.enums.RequestHeaderElement;
import net.tavion.angelboot.common.enums.SystemCode;
import net.tavion.angelboot.common.utils.ObjectMapperUtils;
import net.tavion.angelboot.common.vo.GenericResponse;
import net.tavion.angelboot.gateway.jwt.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Configuration
@Order(-2)
@Slf4j
public class GatewayCreditFilter extends AbstractGatewayFilterFactory {

    @Resource
    ObjectMapper objectMapper;


    public GatewayCreditFilter() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Object config) {
        log.info("进入自定义Credit过滤器");
        return (exchange, chain) -> {


            ServerHttpRequest request =  exchange.getRequest();

            String tokenHeader= request.getHeaders().getFirst(RequestHeaderElement.authorization.getCode());

            if (tokenHeader == null || !tokenHeader.startsWith(JwtUtil.TOKEN_PREFIX) ) {
                ServerHttpResponse response = exchange.getResponse();
                //设置headers
                HttpHeaders httpHeaders = response.getHeaders();
                httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
                httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
                //设置body
                GenericResponse failResponse=new GenericResponse();
                failResponse.setCode(SystemCode.COMMON_AUTHORIZED_FAILURE.getCode());
                failResponse.setMessage(SystemCode.COMMON_AUTHORIZED_FAILURE.getMessage()+"--001");
                byte[] dataBytes= ObjectMapperUtils.writeAsString(failResponse,objectMapper).getBytes();

                DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
                return response.writeWith(Mono.just(bodyDataBuffer));
            }

            return chain.filter(exchange);
        };
    }
    public static class Config {
    }
    @Bean
    public GatewayCreditFilter creditFileterFactory() {
        return new GatewayCreditFilter();
    }
}
